package com.sskj.motherboard.handler;

import com.sskj.motherboard.vo.FrameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class CustomProtocolDecoder extends ByteToMessageDecoder {

    private static final int HEADER_LENGTH = 4;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        ByteBuf data = null;
        try {
            if (byteBuf.readableBytes() < HEADER_LENGTH) {
                return;
            }
            byteBuf.markReaderIndex();

            byte commandCode = byteBuf.readByte();
            byte commandType = byteBuf.readByte();
            int dataLength = byteBuf.readUnsignedShortLE();
            log.info("数据长度:{}", dataLength);

            if (dataLength < 0) {
                log.warn("Invalid data length: {}, closing connection.", dataLength);
                byteBuf.clear(); // 清理非法数据
                channelHandlerContext.close();
                return;
            }

            if (byteBuf.readableBytes() < dataLength) {
                byteBuf.resetReaderIndex();
                return;
            }

            data = byteBuf.readBytes(dataLength);
            log.info("Received packet -> CommandCode: 0x{}, CommandType: 0x{}, Length: {}, Data: {}",
                    Integer.toHexString(commandCode & 0xFF),
                    Integer.toHexString(commandType & 0xFF),
                    dataLength,
                    data.toString(io.netty.util.CharsetUtil.UTF_8));

            FrameMessage frameMessage = new FrameMessage();
            frameMessage.setCommandCode(commandCode);
            frameMessage.setCommandType(commandType);

            byte[] dateBytes;
            if (dataLength == 0) {
                dateBytes = new byte[0];
            } else {
                dateBytes = new byte[dataLength];
                data.readBytes(dateBytes);
            }
            frameMessage.setData(dateBytes);

            list.add(frameMessage);
        } catch (Exception e) {
            log.error("Error decoding packet", e);
            channelHandlerContext.close();
        } finally {
            if (data != null) {
                data.release();
            }
        }
    }
}
